import { migration } from '@src/component/form/util';
import {
  getEnabledCardInfo
} from '@src/api/SettingCusProApi';
import * as StorageUtil from '@src/util/storage.ts'
/* enum */
import ComponentNameEnum from '@model/enum/ComponentNameEnum.ts'
import StorageKeyEnum from '@model/enum/StorageKeyEnum.ts'
import StorageModuleEnum from '@model/enum/StorageModuleEnum'

export default {
  data() {
    return {
      labelAllList: [], // 右侧所有标签选项
      addOnLabelList: this.initData.openSuperCodePro ? void 0 : [], // 右侧所有附加组件
      addOnLabelShowList: [], // 右侧附加组件实际展示
      labelShowList: void 0, // 右侧标签展示选择项
      cardCacheList: void 0, // 右侧标签缓存
      labelPrepared: false,
      labelExtend: false,
      
      headerEl: {
        clientHeight: 0,
        scrollHeight: 0
      },
      moreLabelBtnShow: false,
      moreLabelBtnTop: 0,
      ifResizeWatch: void 0,
      ifResizeObserverSupport: !!window.ResizeObserver,
      isGetCardCached: false,
      isOpenQualityChanged: false
    }
  },
  methods: {
    // 获取接口缓存的标签数据
    getCardCache() {
      // this.cardCacheList = []
      // this.initLabelList()
      // return
      this.api.getCardCache().then(async res => {
        let list = []
        if (res.result) {
          list = res.result
        }
        this.cardCacheList = list
        this.isGetCardCached = true
        
        if (this.isOpenQualityChanged) {
          await this.changeQualityTab()
        }

      }).catch(err => {
        console.log(err)
        this.cardCacheList = []
        this.$message.error(this.$t('customer.detail.taskCard.getCardCache.errorMsg'))
      }).finally(() => {
        this.initLabelList()
      })
    },
    // 通过接口设置缓存的标签数据
    setCardCache() {
      this.api.setCardCache(this.labelShowList).then(res => {
        if (res.code !== 0) {
          this.$message.error(res.message)
        }
      }).catch(err => {
        console.log(err)
        this.$message.error(this.$t('customer.detail.taskCard.setCardCache.errorMsg'))
      })
    },

    // 初始化tab标签列表
    initLabelList () {
      if(!this.addOnLabelList || !this.cardCacheList) {
        return
      }
      let optionList = [
        ...this.sysLabelList,
        ...this.addOnLabelList
      ]
      this.labelAllList = optionList
      if (!this.cardCacheList.length) {
        this.addOnLabelShowList = [...this.addOnLabelList]
        this.labelShowList = optionList.map(v => v.key)
      } else {
        this.addOnLabelShowList = this.addOnLabelList.filter(v => this.cardCacheList.includes(v.key))
        this.labelShowList = optionList.filter(v => this.cardCacheList.includes(v.key)).map(v => v.key)
      }
      this.labelPrepared = true
      this.$nextTick(() => {
        setTimeout(() => {
          this.changeMoreLabelBtn()
          this.initRightTabBar()
        }, 0)
      })
    },

    // tab标签展示变更
    labelShowListChange(labelShowList) {
      let addOnLabelShowList = this.labelAllList.filter(label => this.isAddOn(label.key) && labelShowList.includes(label.key))
      this.$set(this, 'addOnLabelShowList', addOnLabelShowList)
      if (!labelShowList.includes(this.currTabRight)) {
        let firstLabel = document.querySelector('.content-right-tabs .el-tabs__item')
        if(!firstLabel) return
        this.currTabRight = firstLabel.id.slice(4)
      }
      this.setCardCache()
      !this.ifResizeObserverSupport && this.changeMoreLabelBtnBefore()
    },
    // 更改选中的tab
    currTabRightChange(item) {
      let trackData
      if (this.isAddOn(item.tabName)) {
        this.$nextTick(() => {
          let taskDetailCard = this.$refs.taskDetailCard
          taskDetailCard && (taskDetailCard.activeTab = item.tabName.slice(7))
        })
        trackData = item.label
      } else {
        trackData = item.label.replace(/\([^\)]*\)/g, '')
      }
      trackData && this.$track.clickStat(this.$track.formatParams('DETAIL_ADD_ONS_TABS', trackData))
      this.currTabRight = item.tabName
    },
    // 是否是附加组件
    isAddOn (key) {
      return key.startsWith('add-on-')
    },
    // 组件信息和字段信息列表
    async getEnabledCardInfo(){
      try{
        let {result,code,message}=await getEnabledCardInfo({cardType:this.propsForSubComponents.cardType});
        if(code===0){
          result.forEach(card=>{
            card.key = `add-on-${card.id}`
            // 多选格式调整
            card.fields = migration(card.fields || []);
          });
          this.addOnLabelList = result
          this.initLabelList()
        }else{
          this.$message.error(message);
        }
      }catch(err){
        console.error(err);
      }
    },
    changeMoreLabelBtnBefore(...rest) {
      this.$nextTick(() => {
        this.changeMoreLabelBtn(...rest)
      })
    },
    // 改变更多按钮的位置及显示
    changeMoreLabelBtn (type) {
      if (!this.labelPrepared) return
      let headerEl = document.querySelector('.content-right-tabs .el-tabs__nav-wrap')
      if (!headerEl) return
      
      this.setResizeWatch()

      let { clientHeight, scrollHeight } = headerEl
      if(scrollHeight === this.headerEl.scrollHeight && clientHeight === this.headerEl.clientHeight) return
      this.headerEl.clientHeight = clientHeight
      this.headerEl.scrollHeight = scrollHeight

      if (!type || type === 'show') {
        let status
        if (scrollHeight > 100) {
          status = true
        } else {
          status = false
        }
        this.moreLabelBtnShow = status
      }
      if (!type || type === 'pos') {
        this.moreLabelBtnTop = `${clientHeight - 32}px`
      }
    },
    // 展开/收起
    labelExtendChange () {
      this.labelExtend = !this.labelExtend
      this.changeMoreLabelBtnBefore('pos')
    },
    // 设置el-tabs的header元素变化监听
    setResizeWatch() {
      if (this.ifResizeWatch) return
      this.ifResizeWatch = true
      let debounceFn = this.debounce(entries => {
        this.changeMoreLabelBtnBefore()
      }, 50)
      if(this.ifResizeObserverSupport) { // 考虑到onresize事件不一定能及时把握元素高度变化，所以采用ResizeObserver
        const resizeObserver = new ResizeObserver(debounceFn)
        resizeObserver.observe(document.querySelector('.content-right-tabs .el-tabs__nav-scroll'))
      } else { // 兼容处理
        window.onresize = debounceFn
        this.$watch('collapseDirection', () => {
          setTimeout(() => this.changeMoreLabelBtnBefore(), 300)
        })
      }
    },
    // 防抖
    debounce(fn, wait) {
      var timeout = null
      return function(...rest) {
        if(timeout !== null) clearTimeout(timeout)
        timeout = setTimeout(() => fn(...rest), wait)
      }
    },
    async changeQualityTab() {
      await StorageUtil.storageSet(StorageKeyEnum.ProductQualityTab, true, StorageModuleEnum.Task)
      this.cardCacheList.push('quality-info-record')
      this.cardCacheList = [...new Set(this.cardCacheList)]
      this.initLabelList()
      this.labelShowListChange(this.labelShowList)
    }
  },
  mounted() {
    this.getCardCache()
    this.initData.openSuperCodePro && this.getEnabledCardInfo()
  }
}
